package org.moonlight.jvm.classfile.attribute;

import org.moonlight.jvm.classfile.ClassReader;
import org.moonlight.jvm.classfile.constant.StaticConstantPool;

import java.util.HashMap;
import java.util.Map;

/**
 * EnclosingMethod 属性表示一个匿名类或者本地类(local class 个人理解这应该是指在方法内部定义的类).其结构定义如下:
 *   EnclosingMethod_attribute {
 *       u2 attribute_name_index;
 *       u4 attribute_length;
 *       u2 class_index;
 *       u2 method_index;
 *   }
 *
 * @author Moonlight
 * @createTime 2023/8/15 17:38
 **/
public class EnclosingMethodAttribute implements AttributeInfo {

    private final StaticConstantPool scp;
    private int classIdx;
    private int methodIdx;

    public EnclosingMethodAttribute(StaticConstantPool scp) {
        this.scp = scp;
    }

    @Override
    public void readInfo(ClassReader reader) {
        this.classIdx = reader.readUint16();
        this.methodIdx = reader.readUint16();
    }

    public String className() {
        return this.scp.getClassName(this.classIdx);
    }

    public Map<String, String> methodNameAndDescriptor() {
        if (this.methodIdx > 0) {
            return this.scp.getNameAndType(this.methodIdx);
        }
        return new HashMap<>(0);
    }

}
